﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Pong
{    
    public abstract class GameLoop
    {
        protected DateTime lastTick;
        protected bool IsRunning = false;
        public delegate void UpdateHandler(object sender, TimeSpan elapsed);
        public event UpdateHandler Update;
        private const double rate = TimeSpan.TicksPerSecond / 30.0;

        public void Tick()
        {
            DateTime now = DateTime.Now;
            TimeSpan elapsed = now - lastTick;
            long diff = now.Ticks - lastTick.Ticks;

            if (diff > rate)
            {
                lastTick = now;

                if (Update != null)
                    Update(this, elapsed);
            }
        }

        public virtual void Start()
        {
            if (!IsRunning)
            {
                lastTick = DateTime.Now;
                IsRunning = true;
            }
        }

        public virtual void Stop()
        {
            IsRunning = false;
        }
    }

    public class CompositionTargetGameLoop : GameLoop
    {
        public CompositionTargetGameLoop()
        {

        }

        void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            base.Tick();
        }


        public override void Start()
        {
            if (!base.IsRunning)
            {
                CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
                base.Start();
            }
        }



        public override void Stop()
        {
            CompositionTarget.Rendering -= new EventHandler(CompositionTarget_Rendering);
            base.Stop();
        }
    }
}
